#include "fyp/render/XMesh.h"

//------------------------------------------------------------------------------
// additional header includes
#include "fyp/render/ResourceFactory.h"
#include "fyp/core/Vec.h"

#include <d3d9.h>
#include <d3dx9.h>

//------------------------------------------------------------------------------
namespace ming
{
namespace fyp
{
namespace render
{
	//--------------------------------------------------------------------------
	TXMesh::TXMesh(const char *filename, TResourceFactory *resFactory) :
		mResFactory(resFactory),
		mSubMeshCnt(0)
	{
		mXMesh = resFactory->LoadXMesh(filename);

		if(mXMesh)
		{
			DWORD attriTableSz;
			mXMesh->GetAttributeTable(NULL, &attriTableSz);
			mSubMeshCnt = (size_t)attriTableSz;

			IDirect3DVertexBuffer9 *vb = NULL;
			mXMesh->GetVertexBuffer(&vb);

			if(vb)
			{
				D3DXVECTOR3 *dataPtr;
				if(SUCCEEDED(vb->Lock(0, 0, (VOID**)&dataPtr, D3DLOCK_READONLY)))
				{
					D3DXVECTOR3 minPt, maxPt;

					D3DXComputeBoundingBox(
						dataPtr,
						mXMesh->GetNumVertices(),
						mXMesh->GetNumBytesPerVertex(),
						&minPt,
						&maxPt);

					mAABox.setMax( TVec3(maxPt.x, maxPt.y, maxPt.z) );
					mAABox.setMin( TVec3(minPt.x, minPt.y, minPt.z) );

					vb->Unlock();
				}

				vb->Release();
			}
		}
	}
	
	//--------------------------------------------------------------------------
	TXMesh::~TXMesh()
	{
		mResFactory->UnloadXMesh(mXMesh);
	}

	//--------------------------------------------------------------------------
	void TXMesh::Render()
	{
		for(size_t i=0; i<mSubMeshCnt; ++i)
			mXMesh->DrawSubset( (DWORD)i );
	}

	//--------------------------------------------------------------------------
	const TAABox & TXMesh::GetAABox()
	{
		return mAABox;
	}
	
	//--------------------------------------------------------------------------
}
}
}
